import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; // 使用映射路径
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { roomPaths } from './path-data.js';
// 1. 初始化场景、相机、渲染器
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xaaaaaa); // 浅灰背景

const camera = new THREE.PerspectiveCamera(
    75, 
    window.innerWidth / window.innerHeight, 
    0.1, 
    1000
);
camera.position.set(0, 1.6, 5); // 模拟人眼高度（1.6米）

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 2. 添加光源（增强立体感）
const ambientLight = new THREE.AmbientLight(0x404040); // 环境光
scene.add(ambientLight);

// // 4. 添加环境光源
// const environment = new RoomEnvironment();
// const pmremGenerator = new THREE.PMREMGenerator(renderer);
// scene.environment = pmremGenerator.fromScene(environment).texture;

const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); // 方向光
directionalLight.position.set(5, 10, 7);
scene.add(directionalLight);

// 6. 添加控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
controls.minDistance = 2;
controls.maxDistance = 20;

// 7. 键盘移动控制
const moveSpeed = 0.1;
const moveState = { forward: 0, backward: 0, left: 0, right: 0 };
const velocity = new THREE.Vector3();

const onKeyDown = (event) => {
  switch (event.code) {
    case 'KeyW': moveState.forward = 1; break;
    case 'KeyS': moveState.backward = 1; break;
    case 'KeyA': moveState.left = 1; break;
    case 'KeyD': moveState.right = 1; break;
  }
};

const onKeyUp = (event) => {
  switch (event.code) {
    case 'KeyW': moveState.forward = 0; break;
    case 'KeyS': moveState.backward = 0; break;
    case 'KeyA': moveState.left = 0; break;
    case 'KeyD': moveState.right = 0; break;
  }
};

window.addEventListener('keydown', onKeyDown);
window.addEventListener('keyup', onKeyUp);

// 添加箭头指示器功能
function createPathArrows(groundLevel) {
  // const pathPoints = roomPaths.map(p => 
  //   new THREE.Vector3(p.x, groundLevel, p.z)
  // );
  // 示例路径点 - 在实际应用中应从外部数据源获取
  const pathPoints = [
    new THREE.Vector3(0, groundLevel, -3),     // 起点（入口处）
    new THREE.Vector3(-2, groundLevel, -5),    // 路径点1
    new THREE.Vector3(3, groundLevel, -7),     // 路径点2
    new THREE.Vector3(5, groundLevel, -3),     // 路径点3
    new THREE.Vector3(0, groundLevel, 0)       // 终点（房间中心）
  ];
  
  const arrowGroup = new THREE.Group();
  const arrowSize = 0.5;
  
  // 创建箭头形状
  const arrowShape = new THREE.Shape();
  arrowShape.moveTo(0, 0);
  arrowShape.lineTo(-arrowSize, arrowSize);
  arrowShape.lineTo(0, arrowSize * 0.6);
  arrowShape.lineTo(arrowSize, arrowSize);
  arrowShape.lineTo(0, 0);
  
  const arrowGeometry = new THREE.ShapeGeometry(arrowShape);
  const arrowMaterial = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      side: THREE.DoubleSide
  });
  
  // 沿路径创建箭头
  for (let i = 0; i < pathPoints.length - 1; i++) {
      const start = pathPoints[i];
      const end = pathPoints[i + 1];
      
      // 计算箭头位置和方向
      const midPoint = new THREE.Vector3().lerpVectors(start, end, 0.5);
      const direction = new THREE.Vector3().subVectors(end, start).normalize();
      
      // 创建箭头并设置方向
      const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
      arrow.position.copy(midPoint);
      arrow.position.y += 0.02; // 稍微高于地面
      arrow.rotation.y = Math.atan2(direction.x, direction.z);
      arrow.scale.set(0.8, 0.8, 0.8);
      
      arrowGroup.add(arrow);
  }
  
  scene.add(arrowGroup);
  return arrowGroup;
}

// 8. 加载GLB模型
const loader = new GLTFLoader();
let model;
loader.load(
  '../assets/new1.glb',
  (gltf) => {    
    scene.add(gltf.scene); // 将模型添加到场景中
});

// 9. 窗口尺寸自适应
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

// 10. 动画循环
function animate() {
  requestAnimationFrame(animate);
  
  // 键盘移动处理
  velocity.z = moveState.forward - moveState.backward;
  velocity.x = moveState.right - moveState.left;
  velocity.normalize().multiplyScalar(moveSpeed);
  
  camera.translateX(velocity.x);
  camera.translateZ(velocity.z);
  
  controls.update();
  renderer.render(scene, camera);
}

animate();